package cn.swjtuhc.ss.hljapi.controller.admin;

import cn.hutool.core.bean.BeanUtil;
import cn.swjtuhc.ss.hljapi.common.Result;
import cn.swjtuhc.ss.hljapi.mapper.UserMapper;
import cn.swjtuhc.ss.hljapi.pojo.User;
import cn.swjtuhc.ss.hljapi.pojo.response.UserLoginResponse;
import cn.swjtuhc.ss.hljapi.util.StpAdminUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * @author 程序狗没有春天
 * @version 1.00
 * @createTime 2024/8/26 21:01
 */
@Slf4j
@RequestMapping("/admin/user")
@RestController
public class AdminUserController {
    @Autowired
    UserMapper userMapper;
    @PostMapping("/login")
    public Result<UserLoginResponse> login(@RequestBody User user) {
        // 检查用户名和密码是否为空
        if (user.getUsername() == null || user.getPassword() == null) {
            return Result.fail("用户名或密码不能为空");
        }

        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", user.getUsername());
        User exists = userMapper.selectOne(queryWrapper);

        if (exists == null) {
            return Result.fail("用户不存在");
        }

        // 比较密码（在实际应用中，应使用密码加密存储和验证）
        if (!exists.getPassword().equals(user.getPassword())) {
            return Result.fail("密码错误");
        }

        // 登录操作，使用用户ID进行登录
        StpAdminUtil.login(exists.getId());

        // 构建登录响应
        UserLoginResponse response = BeanUtil.copyProperties(exists, UserLoginResponse.class);
        response.setTokenValue(StpAdminUtil.getTokenValue());
        response.setTokenName(StpAdminUtil.getTokenName());

        return Result.success(response);
    }

}
